package com.gowants.pems.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gowants.pems.aspect.Importance;
import com.gowants.pems.aspect.OperType;
import com.gowants.pems.aspect.ScmsAopLog;
import com.gowants.pems.config.AccessLimit;
import com.gowants.pems.model.SysAppUpdate;
import com.gowants.pems.model.SysDict;
import com.gowants.pems.service.SysAppUpdateService;
import com.gowants.pems.service.SysDictService;
import com.gowants.pems.util.Const;
import com.gowants.pems.util.DateUtil;
import com.gowants.pems.util.JSONList;
import com.gowants.pems.util.JSONMap;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping(value = "/sysAppUpdate/")
public class SysAppUpdateController extends BaseController{
	
	@Autowired
	private SysAppUpdateService scmsAppUpdateService;
	@Autowired
	private SysDictService ScmsDictService;
	
	 @RequestMapping(value = "getList", method = RequestMethod.POST)
	 @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
	    @ScmsAopLog(description = "App更新列表查看", opType = OperType.execute, importance = Importance.commonly)
	    public JSONMap getList(@RequestParam(defaultValue = "1", required = false, value = "page") int page,
	            @RequestParam(defaultValue = "10", required = false, value = "limit") int limit,
	            @RequestParam(defaultValue = "", required = false, value = "reqData") String reqData,
	            HttpServletRequest req) 
	    {
	        if (!isPower("/sysAppUpdate/getList.do")) 
	        {
	            return doResponse(req, "TSMS_0000228");
	        }
	        JSONMap resultMap = new JSONMap();
	        SysAppUpdate record = new SysAppUpdate();
	        if (!"".equals(reqData)) 
	        {
	            JSONList jsonCondition = getCondition(reqData);
	           
	            for (Object cond : jsonCondition) {
	                this.buildCondition(cond, record);
	            }
	        }
	        // 设置分页查询信息
	        PageHelper.startPage(page, limit);
	        List<SysAppUpdate> list = scmsAppUpdateService.select(record);
	        PageInfo<SysAppUpdate> pageInfo = new PageInfo<SysAppUpdate>(list);
	        // 赋值方法
	        pageSetData(req, resultMap, page,  limit, pageInfo.getPages(),"", list, pageInfo.getTotal());

	        return doResponse(req, "", resultMap);
	    }
	 
	 private void buildCondition(Object cond, SysAppUpdate record) 
	    {
	        JSONMap condition = JSONMap.parseJSONMap(cond.toString());

	        String field = condition.getString("field");
	        String keyword = condition.getString("keyword");

	        if (StringUtils.isNotEmpty(field) && StringUtils.isNotEmpty(keyword)) 
	        {
	            switch (field) 
	            {
	                case "id":
	                    record.setId(keyword);
	                    break;
	                case "code":
	                    record.setCode(keyword);
	                    break;
	                
	            }
	        }
	    }
	 
	 /**
	     * <保存>
	     * @param request
	     * @param req
	     * @return
	     * @remake 
	     */
	    @RequestMapping(value = "save", method = RequestMethod.POST)
		@AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
	    @ScmsAopLog(description = "App更新保存", opType = OperType.execute, importance = Importance.commonly)
	    public JSONMap save(String request, HttpServletRequest req) 
	    {
	        if (!isPower("/sysAppUpdate/save.do")) 
	        {
	            return doResponse(req, "TSMS_0000228");
	        }
	        String code = "TSMS_0000036";
	        try
	        {
	        	SysAppUpdate record = getRequestBody(request, SysAppUpdate.class);
	        	
	            int count = scmsAppUpdateService.saveCheck(record);
	            if(count > 0) 
	            {
	                return doResponse(req, "TSMS_0000246", null);
	            }
	            record.setId(UUID.randomUUID().toString().replaceAll("-", ""));
	            record.setCreateTime(DateUtil.getDate());
	            int exeNum = scmsAppUpdateService.save(record);
	            if(exeNum > 0) 
	            {
	                code = "TSMS_0000001";
	            }
	        }
	        catch (Exception e)
	        {
	            code = e.getMessage();
	        }
	        
	        return doResponse(req, code, null);
	    }
	    
	    /**
	     * <删除>
	     * @param request
	     * @param req
	     * @return
	     * @remake 
	     */
	    @RequestMapping(value = "delete", method = RequestMethod.POST)
		@AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
	    @ScmsAopLog(description = "App更新删除", opType = OperType.execute, importance = Importance.commonly)
	    public JSONMap delete(String request, HttpServletRequest req) 
	    {
	        if (!isPower("/sysAppUpdate/delete.do")) 
	        {
	            return doResponse(req, "TSMS_0000228");
	        }
	        String code = "TSMS_0000048";
	        try
	        {
	            JSONMap requestBody = getRequestBody(request);
	            String id = requestBody.getString("id");
	            int exeNum = scmsAppUpdateService.delete(id);
	            if(exeNum > 0) 
	            {
	                code = "TSMS_0000050";
	            }
	        }
	        catch (Exception e)
	        {
	            code = e.getMessage();
	        }
	        return doResponse(req, code, null);
	    }
	    
	    /**
	     * <修改>
	     * @param request
	     * @param req
	     * @return
	     * @remake 
	     */
	    @RequestMapping(value = "update")
		@AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
	    @ScmsAopLog(description = "App更新修改", opType = OperType.execute, importance = Importance.important)
	    public JSONMap update(String request, HttpServletRequest req) 
	    {
	        if (!isPower("/sysAppUpdate/update.do")) 
	        {
	            return doResponse(req, "TSMS_0000228");
	        }
	        String code = "TSMS_0000053";
	        try 
	        {   
	        	SysAppUpdate record = getRequestBody(request, SysAppUpdate.class);
	            int count = scmsAppUpdateService.saveCheck(record);
	            if(count > 0)
	            {
	                return doResponse(req, "TSMS_0000246", null);
	            }
	            int exeNum = scmsAppUpdateService.update(record);
	            if(exeNum > 0) 
	            {
	                code = "TSMS_0000002";
	            }
	               
	        } 
	        catch (Exception e) 
	        {
	            code = e.getMessage();
	        }

	        return doResponse(req, code, null);
	    } 
	    
	    
	    @RequestMapping(value = "selectOne")
		@AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
	    @ScmsAopLog(description = "App更新查询", opType = OperType.execute, importance = Importance.important)
	    public JSONMap selectOne(String request, HttpServletRequest req) 
	    {
	    	String code="";
	    	try
	        {
	    		 if (!isPower("/sysAppUpdate/selectOne.do")) 
	 	        {
	 	            return doResponse(req, "TSMS_0000228");
	 	        }
	            JSONMap requestBody = getRequestBody(request);
	            String id = requestBody.getString("id");
	            SysAppUpdate record =scmsAppUpdateService.selectOne(id);
	            return doResponse(req, code, record);
	        } 
	        catch (Exception e) 
	        {
	            code = e.getMessage();
	        }

	        return doResponse(req, code, null);
	    }
	    
	    @RequestMapping(value = "selectByCode")
		@AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
	    @ScmsAopLog(description = "App更新获取", opType = OperType.execute, importance = Importance.important)
	    public JSONMap selectByCode(String request, HttpServletRequest req) 
	    {
	    	String code="";
	    	try
	        {
	            JSONMap requestBody = getRequestBody(request);
	            String codes = requestBody.getString("code");
	            SysAppUpdate record =scmsAppUpdateService.selectByCode(codes);
	            return doResponse(req, code, record);
	        } 
	        catch (Exception e) 
	        {
	            code = e.getMessage();
	        }
	        return doResponse(req, code, null);
	    }
	    
	    @RequestMapping(value = "uploadApk")
		@AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
		public JSONMap uploadApk(MultipartFile myFile,  HttpServletRequest req) {
			String code = "";
			try {
				
				// 校验上传文件
				int checkResult = scmsAppUpdateService.uploadCheck(myFile, Const.sys_app_update_type, Const.sys_app_update_size);

				// 文件超出限制大小
				if (checkResult == -1) {
					return doResponse(req, "TSMS_0000025");
				}

				// 文件格式不对
				if (checkResult == 0) {
					return doResponse(req, "TSMS_0000026");
				}
				String path = scmsAppUpdateService.upload(myFile, Const.sys_app_update_path, null, Const.sys_app_update_mapping, true, true);
				if ("".equals(path)) {
					return doResponse(req, "TSMS_0000089");
				}
				JSONMap resultMap = new JSONMap();
				resultMap.put("path", path);
				return doResponse(req, code, resultMap);
				
			} catch (Exception e) {
				code = e.getMessage();
				return doResponse(req, code, null);
			}
		}
	    
	    /**
		 * 获取字典
		 * 
		 * @param request={"dictId":"","groupId":""}
		 * @param req
		 * @return
		 */
		@RequestMapping(value = "dict")
		@AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
		public JSONMap dict(String request, HttpServletRequest req) {
			SysDict ScmsDict = new SysDict();
			ScmsDict.setGroupId("sys_app_update_code");
			List<SysDict> dictList = ScmsDictService.selectList(ScmsDict);
			JSONList jsList=new JSONList();
			for(SysDict sd:dictList) {
				JSONMap js=new JSONMap();
				js.put("dictId", sd.getDictName());
				js.put("dictName", sd.getRemarks());
				js.put("groupId", sd.getGroupId());
				jsList.add(js);
			}
			return doResponse(req, "", jsList);

		}

}
